#include "threadpool.h"

static void* ThreadPollWorker(void *arg)
{
    TaskQueue* queue = (TaskQueue*)arg;
    while (true)
    {
        Task task;
        if (!QueuePopTask(queue,&task))
        {
            break;
        }
        task.function(task.arg);
    }
    return NULL;
}

ThreadPool* createThreadPool(int worker_number,int queuesize)
{
    ThreadPool* threadpool = (ThreadPool*)malloc(sizeof(ThreadPool));
    if (threadpool == NULL)
    {
        return NULL;
    }
    threadpool->workers = (pthread_t*)malloc(worker_number * sizeof(pthread_t));
    if (threadpool->workers == NULL)
    {
        return NULL;
    }

    threadpool->taskqueue = QueueInit(queuesize);
    if (threadpool->taskqueue == NULL)
    {
        return NULL;
    }
    
    for (size_t i = 0; i < worker_number; i++)
    {
        pthread_create(&threadpool->workers[i],NULL,ThreadPollWorker,(void*)threadpool->taskqueue);
    }
    return threadpool;
}

void ThreadPollPostTask(ThreadPool* threadpool,Task *task)
{
    if (threadpool == NULL || task == NULL)
    {
        return;
    }
    QueuePushTask(threadpool->taskqueue,task);
}

void destroyThreadPool(ThreadPool* threadpool)
{
    if (threadpool == NULL)
    {
        return;
    }
    QueueCancel(threadpool->taskqueue);
    free(threadpool->workers);
    free(threadpool);
}